import asyncio
import json

from aiohttp import web


class SSEData:
    def __init__(self, data, d_type):
        self.data = {
            "content": data,
            "type": d_type,
        }

    def data_pack(self):
        data = f"data: {json.dumps(self.data, ensure_ascii=False)}\n\n"
        return data.encode("utf-8")


async def sse_handler(request):
    response = web.StreamResponse(
        status=200,
        reason='OK',
        headers={
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive'
        }
    )
    await response.prepare(request)
    result = {"code": 0, "msg": "ok"}
    message = json.dumps(result)
    lst_message = list(message)
    lst_message = ["12", "23", "34", "45"]
    lst_message.reverse()
    try:
        while True:
            t = lst_message.pop()
            print(t)
            await response.write(f"data: {t}\n\n".encode('utf-8'))
            await response.drain()
            await asyncio.sleep(1)  # 每隔 1 秒发送一次消息
    except Exception as e:
        print(e)
    finally:
        await response.write_eof()
        return response

async def sse_output(s_list: list[str]):
    for x in s_list:
        yield x

if __name__ == '__main__':
    app = web.Application()
    app.router.add_post('/stream', sse_handler)
    web.run_app(app, port=8081)
